﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace RDJTProtocolServer
{
    class Rdjtp
    {
        public RdjtpRequest Request { get; private set; }
        public RdjtpResponse Response { get; set; }

        //public enum Method
        //{
        //    create, read, update, delete, echo
        //}

        private string _message;

        public Rdjtp(string message)
        {
            _message = message;
        }

        public bool ExecuteRequest()
        {
            try
            {
                var request = JsonConvert.DeserializeObject<RdjtpRequest>(_message);
                Request = request;
            }
            catch (JsonReaderException)
            {
                Response = new RdjtpResponse(RdjtpStatus.Error);
                return false;
            }

            Response = new RdjtpResponse();

            if (!HeadersValid())
            {
                Response.Status = "4 ";

                if (Request.Method == null)
                {
                    Response.Status += "missing method, ";
                }
                else
                {
                    if (Request.Method != "create" &&
                    Request.Method != "read" &&
                    Request.Method != "update" &&
                    Request.Method != "delete" &&
                    Request.Method != "echo")
                    {
                        Response.Status += "illegal method, ";
                    }
                }
                if (Request.Path == null) Response.Status += "missing path, ";
                if (Request.Date == 0) Response.Status += "missing date, ";
                if (Request.Date < 0 || Request.Date > DateTimeOffset.Now.ToUnixTimeSeconds()) Response.Status += "illegal date, ";
                if ((Request.Method == "create" || Request.Method == "update") && Request.Body == null) Response.Status += "missing body, ";

                return false;
            }

            Response = new RdjtpResponse(RdjtpStatus.Ok);
            return true;
        }

        private bool HeadersValid()
        {
            // TODO: apparently, when "echo" requested, no need to check for path

            bool mandatoryHeadersPresent =
                Request.Method == null ||
                Request.Path == null ||
                Request.Date == 0 ? false : true;

            bool mandatoryHeadersCorrect =
                Request.Method == "create" ||
                Request.Method == "read" ||
                Request.Method == "update" ||
                Request.Method == "delete" ||
                Request.Method == "echo" ? true : false;

            bool bodyPresentIfNeeded =
                (Request.Method == "create" ||
                Request.Method == "update") &&
                Request.Body == null ? false : true;

            return mandatoryHeadersCorrect && mandatoryHeadersCorrect && bodyPresentIfNeeded;
        }
    }
}
